package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;

@Slf4j
@Service
public class DishServiceImpl implements DishService {
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private DishFlavorMapper dishFlavorMapper;
    @Autowired
    private SetmealDishMapper setmealDishMapper;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    /**
     * 新增菜品，同时插入菜品对应的数据，需要操作两张表：dish、dish_flavor
     *
     * @param dishDTO
     */
    @Override
    @Transactional
    public void save(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        dish.setCreateTime(LocalDateTime.now());
        dish.setUpdateTime(LocalDateTime.now());
        dish.setCreateUser(BaseContext.getCurrentId());
        dish.setUpdateUser(BaseContext.getCurrentId());
        dishMapper.insertDish(dish);

        List<DishFlavor> flavors = dishDTO.getFlavors();
        // 获取插入到数据库的菜品的id
        // 获取菜品ID
        Long dishId = dish.getId();
        // 如果口味列表不为空，则批量插入口味信息
        if (flavors != null && !flavors.isEmpty()) {
            // 为每个口味设置对应的菜品ID
            for (DishFlavor flavor : flavors) {
                flavor.setDishId(dishId);
            }
            // 批量插入口味数据
            dishFlavorMapper.insertBatch(flavors);
        }
        // 删除缓存
        String key = "dish_" + dishDTO.getCategoryId();

        deleteCache(key);
    }

    /**
     * 菜品分页查询
     *
     * @param dishPageQueryDTO
     * @return
     */
    @Override
    public PageResult selectPage(DishPageQueryDTO dishPageQueryDTO) {
        PageHelper.startPage(dishPageQueryDTO.getPage(), dishPageQueryDTO.getPageSize());
        List<DishVO> row = dishMapper.pageQuery(dishPageQueryDTO);

        Page<DishVO> total = (Page<DishVO>) row;

        return new PageResult(total.getTotal(), total.getResult());
    }

    /**
     * 批量删除菜品
     *
     * @param ids
     */
    @Override
    @Transactional
    public void delete(List<Long> ids) {

        //判断是否有起售中的菜品
        for (Long id : ids) {
            Dish dish = dishMapper.getById(id);
            //判断是否起售
            if (dish.getStatus() == StatusConstant.ENABLE) {
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
        }
        //判断当前菜品是否关联了套餐
        List<Long> setmealIds = setmealDishMapper.getSetmealIdByDishId(ids);
        if (setmealIds != null && !setmealIds.isEmpty()) {
            //当前菜品有套餐关联，不能删除
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }
        // 删除菜品基本信息
        dishMapper.deleteDish(ids);
// 删除菜品对应的口味数据
        dishFlavorMapper.deleteByDishId(ids);
        // 删除缓存
        deleteCache("dish_*");
    }

    /**
     * 根据id查询菜品和对应的口味数据
     *
     * @param id
     * @return
     */
    @Override
    public DishVO getById(Long id) {
        return dishMapper.getDishById(id);
    }

    /**
     * 修改菜品
     *
     * @param dishDTO
     */
    @Override
    @Transactional
    public void update(DishDTO dishDTO) {
        // 创建一个Dish对象
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        //更新菜品时间和修改人
        dish.setUpdateTime(LocalDateTime.now());
        dish.setUpdateUser(BaseContext.getCurrentId());
//需要传入dish才能更新时间和修改人
        dishMapper.update(dish);
        // 删除当前菜品对应的口味数据
        dishFlavorMapper.deleteByDishId(Arrays.asList(dishDTO.getId()));
        // 插入当前菜品对应的口味数据
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (flavors != null && !flavors.isEmpty()) {
            // 重新插入当前菜品对应的口味数据
            for (DishFlavor flavor : flavors) {
                flavor.setDishId(dishDTO.getId());
            }
            dishFlavorMapper.insertBatch(flavors);
        }
        // 删除缓存
        deleteCache("dish_*");
    }

    /**
     * 根据分类id查询菜品
     *
     * @param categoryId
     * @return
     */
    @Override
    public List<Dish> getByCategoryId(Long categoryId) {
        return dishMapper.getByCategoryId(categoryId);
    }

    /**
     * 更新菜品状态（起售/停售）
     */
    @Override
    @Transactional
    public void updateStatus(Integer status, Long id) {
        // 构建菜品对象，仅设置需要更新的字段
        Dish dish = Dish.builder()
                .id(id)
                .status(status)
                .updateTime(LocalDateTime.now())
                .updateUser(BaseContext.getCurrentId()) // 当前操作人
                .build();

        // 调用mapper更新状态
        dishMapper.updateStatus(dish);
        // 删除缓存
        deleteCache("dish_*");
    }


    /**
     * 条件查询菜品和口味
     *
     * @param dishList 菜品列表
     * @return 包含口味信息的菜品VO列表
     */
    public List<DishVO> listWithFlavor(List<Dish> dishList) {
        List<DishVO> dishVOList = new ArrayList<>();

        // 遍历菜品列表，为每个菜品查询对应的口味信息
        for (Dish dish : dishList) {
            // 根据菜品id查询菜品和口味信息
            DishVO dishVO = dishMapper.getDishById(dish.getId());
            dishVOList.add(dishVO);
        }

        return dishVOList;
    }

    /**
     * 删除缓存
     */
    public void deleteCache(String  key){
        Set keys = redisTemplate.keys(key);
        redisTemplate.delete(keys);
    }
}
